#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2012/02/13

Module with the class that counts a html tag.
Uses the Beautiful Soup parser

@author: João Vitor Machado Batista nº 5479
'''

from BeautifulSoup import BeautifulSoup
import urllib2
import wx

class tagsCounter:

    def getTabCount(self, urlText, tag):
        '''
            gets the count for a given tag and url
            uses google ip to check connection status
        '''
          
        connectionStatus = self.checkConnection()

        print connectionStatus

        if(connectionStatus == False):
            dialog = '''Check your internet connection!'''
            dlg2 = wx.MessageDialog(None, dialog, "Confirm", wx.OK)
            result = dlg2.ShowModal()
            dlg2.Destroy()
            return 'No internet Connection\n'

        else:
        
            try:
                url = urllib2.urlopen(urlText, timeout=10)
                pass

            except:
                dialog = '''Can't open the url!'''
                dlg2 = wx.MessageDialog(None, dialog, "Confirm", wx.OK)
                result = dlg2.ShowModal()
                dlg2.Destroy()
                return '''Can''t open the url: {0}!\n'''.format(urlText)

            try:
                doc = url.read()
                soup = BeautifulSoup(''.join(doc))
                tagList = soup.findAll(tag)
                return len(tagList)
                        
            except:
                dialog = '''Can't count tags!\n'''
                dlg2 = wx.MessageDialog(None, dialog, "Confirm", wx.OK)
                result = dlg2.ShowModal()
                dlg2.Destroy()
                return dialog

            pass

        pass

    def checkConnection(self):
        '''
            checks the internet connection status using google.com ip
            ir order to bypass dns problems

            http://stackoverflow.com/questions/3764291/checking-network-connection
            
        '''
        
        try:
            response=urllib2.urlopen('http://173.194.67.106',timeout=1)
            return True
        
        except urllib2.URLError as err: pass
        return False
    
        
